package top.v5it.japi.plus.core.spring.web.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import top.v5it.japi.plus.common.func.MethodTemplate;
import top.v5it.japi.plus.core.ConstantPool;
import top.v5it.japi.plus.common.tuple.Tuple5;
import top.v5it.japi.plus.core.api.Result;
import top.v5it.japi.plus.core.exception.JapiSignatureException;
import top.v5it.japi.plus.core.util.JapiSecureUtil;

import static top.v5it.japi.plus.common.ConstantCommon.LOG_DIVIDING_LINE;

/**
 * HMAC-SHA256签名及响应结果包装
 *
 * @author zhanpu
 * @date 2022/6/10
 */
@Slf4j
public class JapiHmacSignatureResponseWrapper implements JapiResponseWrapper {

    @Override
    public Result wrapper(Object body) {
        final Tuple5<Long, String, String, String, String> require = require();
        final String message = buildMessage(require.getOne(), require.getTwo(), body.toString());
        log.debug("{}构造签名串\n{}{}", LOG_DIVIDING_LINE, message, LOG_DIVIDING_LINE);
        final String signature =
                MethodTemplate.executeWithException(() -> JapiSecureUtil.hmacSignature(message)
                        , () -> new JapiSignatureException("签名失败"));

        log.debug("{}响应签名值\n{}{}", LOG_DIVIDING_LINE, signature, LOG_DIVIDING_LINE);
        final MultiValueMap<String, String> headerMap = new LinkedMultiValueMap<>();
        headerMap.add(ConstantPool.getHeadTimestampName(), require.getOne() + ConstantPool.EMPTY);
        headerMap.add(ConstantPool.getHeadChannelName(), require.getFive());
        headerMap.add(ConstantPool.getHeadNonceName(), require.getTwo());
        headerMap.add(ConstantPool.HEAD_REQUEST_ID_NAME, require.getThree());
        headerMap.add(ConstantPool.getHeadSignatureName(), signature);

        return Result.of(body, headerMap);
    }
}
